<!-- src/components/Analytics.vue -->
<template>
  <div class="analytics">
    <!-- 时间范围选择 -->
    <div class="time-range-selector">
      <div class="range-buttons">
        <button 
          v-for="range in timeRanges" 
          :key="range.value"
          @click="selectTimeRange(range.value)"
          :class="['range-btn', { active: selectedRange === range.value }]"
        >
          {{ range.label }}
        </button>
      </div>
      
      <div class="custom-range">
        <input 
          v-model="customRange.start" 
          type="date" 
          class="date-input"
        />
        <span>至</span>
        <input 
          v-model="customRange.end" 
          type="date" 
          class="date-input"
        />
        <button @click="applyCustomRange" class="btn btn-primary">应用</button>
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <div class="metrics-grid">
      <div class="metric-card">
        <div class="metric-header">
          <h4>学员增长</h4>
          <i class="icon-users"></i>
        </div>
        <div class="metric-value">
          {{ formatNumber(analytics.studentGrowth.current) }}
        </div>
        <div class="metric-change" :class="getChangeClass(analytics.studentGrowth.change)">
          <i :class="getChangeIcon(analytics.studentGrowth.change)"></i>
          {{ Math.abs(analytics.studentGrowth.change) }}%
          <span class="change-label">较上期</span>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-header">
          <h4>课程完成率</h4>
          <i class="icon-book"></i>
        </div>
        <div class="metric-value">
          {{ analytics.courseCompletion.rate }}%
        </div>
        <div class="metric-change" :class="getChangeClass(analytics.courseCompletion.change)">
          <i :class="getChangeIcon(analytics.courseCompletion.change)"></i>
          {{ Math.abs(analytics.courseCompletion.change) }}%
          <span class="change-label">较上期</span>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-header">
          <h4>平均学习时长</h4>
          <i class="icon-clock"></i>
        </div>
        <div class="metric-value">
          {{ analytics.avgStudyTime.hours }}h
        </div>
        <div class="metric-change" :class="getChangeClass(analytics.avgStudyTime.change)">
          <i :class="getChangeIcon(analytics.avgStudyTime.change)"></i>
          {{ Math.abs(analytics.avgStudyTime.change) }}%
          <span class="change-label">较上期</span>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-header">
          <h4>教师活跃度</h4>
          <i class="icon-user-check"></i>
        </div>
        <div class="metric-value">
          {{ analytics.teacherActivity.rate }}%
        </div>
        <div class="metric-change" :class="getChangeClass(analytics.teacherActivity.change)">
          <i :class="getChangeIcon(analytics.teacherActivity.change)"></i>
          {{ Math.abs(analytics.teacherActivity.change) }}%
          <span class="change-label">较上期</span>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <div class="chart-row">
        <!-- 学员注册趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>学员注册趋势</h3>
            <div class="chart-actions">
              <button @click="exportChart('student-trend')" class="btn-icon">
                <i class="icon-download"></i>
              </button>
            </div>
          </div>
          <div class="chart-content" id="student-trend-chart" ref="studentTrendChart">
            <div class="chart-placeholder">
              <p>学员注册趋势图表</p>
              <small>建议集成 ECharts 或 Chart.js</small>
            </div>
          </div>
        </div>

        <!-- 课程分类统计 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>课程分类统计</h3>
            <div class="chart-actions">
              <button @click="exportChart('course-category')" class="btn-icon">
                <i class="icon-download"></i>
              </button>
            </div>
          </div>
          <div class="chart-content" id="course-category-chart" ref="courseCategoryChart">
            <div class="chart-placeholder">
              <p>课程分类饼图</p>
              <small>建议集成 ECharts 或 Chart.js</small>
            </div>
          </div>
        </div>
      </div>

      <div class="chart-row">
        <!-- 学习时长分布 -->
        <div class="chart-card full-width">
          <div class="chart-header">
            <h3>学习时长分布</h3>
            <div class="chart-filters">
              <select v-model="studyTimeFilter" @change="updateStudyTimeChart">
                <option value="daily">按日</option>
                <option value="weekly">按周</option>
                <option value="monthly">按月</option>
              </select>
              <button @click="exportChart('study-time')" class="btn-icon">
                <i class="icon-download"></i>
              </button>
            </div>
          </div>
          <div class="chart-content" id="study-time-chart" ref="studyTimeChart">
            <div class="chart-placeholder">
              <p>学习时长分布柱状图</p>
              <small>建议集成 ECharts 或 Chart.js</small>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-tables">
      <div class="table-row">
        <!-- 热门课程排行 -->
        <div class="table-card">
          <div class="table-header">
            <h3>热门课程排行</h3>
            <button @click="exportTable('popular-courses')" class="btn btn-outline">
              <i class="icon-download"></i>导出
            </button>
          </div>
          <div class="table-content">
            <table class="ranking-table">
              <thead>
                <tr>
                  <th>排名</th>
                  <th>课程名称</th>
                  <th>报名人数</th>
                  <th>完成率</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(course, index) in popularCourses" :key="course.id">
                  <td>
                    <span class="rank" :class="`rank-${Math.min(index + 1, 3)}`">
                      {{ index + 1 }}
                    </span>
                  </td>
                  <td>{{ course.title }}</td>
                  <td>{{ course.enrollment_count }}</td>
                  <td>
                    <div class="progress-bar">
                      <div 
                        class="progress-fill" 
                        :style="{ width: course.completion_rate + '%' }"
                      ></div>
                      <span class="progress-text">{{ course.completion_rate }}%</span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 活跃教师排行 -->
        <div class="table-card">
          <div class="table-header">
            <h3>活跃教师排行</h3>
            <button @click="exportTable('active-teachers')" class="btn btn-outline">
              <i class="icon-download"></i>导出
            </button>
          </div>
          <div class="table-content">
            <table class="ranking-table">
              <thead>
                <tr>
                  <th>排名</th>
                  <th>教师姓名</th>
                  <th>授课场次</th>
                  <th>平均评分</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(teacher, index) in activeTeachers" :key="teacher.id">
                  <td>
                    <span class="rank" :class="`rank-${Math.min(index + 1, 3)}`">
                      {{ index + 1 }}
                    </span>
                  </td>
                  <td>{{ teacher.name }}</td>
                  <td>{{ teacher.sessions_count }}</td>
                  <td>
                    <div class="rating">
                      <span class="rating-value">{{ teacher.rating }}</span>
                      <div class="stars">
                        <i v-for="star in 5" :key="star" 
                           :class="['icon-star', { filled: star <= Math.round(teacher.rating) }]">
                        </i>
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 地区分布 -->
    <div class="region-analysis">
      <div class="chart-card">
        <div class="chart-header">
          <h3>学员地区分布</h3>
          <div class="chart-actions">
            <select v-model="regionMetric" @change="updateRegionChart">
              <option value="count">学员数量</option>
              <option value="completion">完成率</option>
              <option value="activity">活跃度</option>
            </select>
            <button @click="exportChart('region-distribution')" class="btn-icon">
              <i class="icon-download"></i>
            </button>
          </div>
        </div>
        <div class="chart-content region-chart" ref="regionChart">
          <div class="chart-placeholder">
            <p>地区分布地图</p>
            <small>建议集成地图组件</small>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'

// 响应式数据
const loading = ref(false)
const selectedRange = ref('7d')
const studyTimeFilter = ref('daily')
const regionMetric = ref('count')

const customRange = reactive({
  start: '',
  end: ''
})

// 时间范围选项
const timeRanges = [
  { label: '最近7天', value: '7d' },
  { label: '最近30天', value: '30d' },
  { label: '最近90天', value: '90d' },
  { label: '最近一年', value: '1y' }
]

// 分析数据
const analytics = ref({
  studentGrowth: {
    current: 2543,
    change: 12.5
  },
  courseCompletion: {
    rate: 78.5,
    change: -2.3
  },
  avgStudyTime: {
    hours: 45.2,
    change: 8.7
  },
  teacherActivity: {
    rate: 92.1,
    change: 5.4
  }
})

// 热门课程数据
const popularCourses = ref([
  {
    id: 1,
    title: '农业种植技术基础',
    enrollment_count: 1250,
    completion_rate: 85
  },
  {
    id: 2,
    title: '现代养殖管理',
    enrollment_count: 987,
    completion_rate: 78
  },
  {
    id: 3,
    title: '农产品电商运营',
    enrollment_count: 856,
    completion_rate: 92
  },
  {
    id: 4,
    title: '绿色农业发展',
    enrollment_count: 743,
    completion_rate: 76
  },
  {
    id: 5,
    title: '农机设备操作',
    enrollment_count: 692,
    completion_rate: 83
  }
])

// 活跃教师数据
const activeTeachers = ref([
  {
    id: 1,
    name: '张教授',
    sessions_count: 156,
    rating: 4.8
  },
  {
    id: 2,
    name: '李老师',
    sessions_count: 142,
    rating: 4.6
  },
  {
    id: 3,
    name: '王专家',
    sessions_count: 128,
    rating: 4.9
  },
  {
    id: 4,
    name: '刘讲师',
    sessions_count: 115,
    rating: 4.5
  },
  {
    id: 5,
    name: '陈博士',
    sessions_count: 103,
    rating: 4.7
  }
])

// 方法
const selectTimeRange = (range) => {
  selectedRange.value = range
  fetchAnalyticsData()
}

const applyCustomRange = () => {
  if (customRange.start && customRange.end) {
    selectedRange.value = 'custom'
    fetchAnalyticsData()
  }
}

const fetchAnalyticsData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用实际的API
    console.log('获取分析数据', selectedRange.value)
  } catch (error) {
    console.error('获取分析数据失败:', error)
  } finally {
    loading.value = false
  }
}

const updateStudyTimeChart = () => {
  console.log('更新学习时长图表', studyTimeFilter.value)
}

const updateRegionChart = () => {
  console.log('更新地区图表', regionMetric.value)
}

const exportChart = (chartId) => {
  console.log('导出图表', chartId)
}

const exportTable = (tableId) => {
  console.log('导出表格', tableId)
}

const getChangeClass = (change) => {
  return change >= 0 ? 'positive' : 'negative'
}

const getChangeIcon = (change) => {
  return change >= 0 ? 'icon-trending-up' : 'icon-trending-down'
}

const formatNumber = (num) => {
  return num.toLocaleString()
}

// 生命周期
onMounted(() => {
  fetchAnalyticsData()
})
</script>

<style scoped>
.analytics {
  padding: 20px;
}

.time-range-selector {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.range-buttons {
  display: flex;
  gap: 8px;
}

.range-btn {
  padding: 8px 16px;
  border: 1px solid #D1D5DB;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.range-btn:hover {
  background: #F3F4F6;
}

.range-btn.active {
  background: #4F46E5;
  color: white;
  border-color: #4F46E5;
}

.custom-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-input {
  padding: 8px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
  font-size: 14px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.metric-card {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.metric-header h4 {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
  font-weight: 500;
}

.metric-header i {
  color: #9CA3AF;
  font-size: 20px;
}

.metric-value {
  font-size: 32px;
  font-weight: bold;
  color: #1F2937;
  margin-bottom: 8px;
}

.metric-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  font-weight: 500;
}

.metric-change.positive {
  color: #10B981;
}

.metric-change.negative {
  color: #EF4444;
}

.change-label {
  color: #6B7280;
  font-weight: normal;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 24px;
}

.chart-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.chart-header {
  padding: 20px;
  border-bottom: 1px solid #E5E7EB;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  color: #1F2937;
  font-size: 18px;
}

.chart-actions, .chart-filters {
  display: flex;
  gap: 8px;
  align-items: center;
}

.chart-content {
  padding: 20px;
  min-height: 300px;
}

.chart-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #F9FAFB;
  border-radius: 6px;
  color: #6B7280;
  text-align: center;
}

.region-chart {
  min-height: 400px;
}

.data-tables {
  margin-bottom: 24px;
}

.table-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table-header {
  padding: 20px;
  border-bottom: 1px solid #E5E7EB;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  color: #1F2937;
  font-size: 18px;
}

.table-content {
  padding: 20px;
}

.ranking-table {
  width: 100%;
  border-collapse: collapse;
}

.ranking-table th,
.ranking-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #F3F4F6;
}

.ranking-table th {
  font-weight: 600;
  color: #374151;
  background: #F9FAFB;
}

.rank {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 12px;
  background: #F3F4F6;
  color: #6B7280;
}

.rank.rank-1 {
  background: #FEF3C7;
  color: #92400E;
}

.rank.rank-2 {
  background: #E5E7EB;
  color: #374151;
}

.rank.rank-3 {
  background: #FEE2E2;
  color: #DC2626;
}

.progress-bar {
  position: relative;
  width: 100%;
  height: 20px;
  background: #F3F4F6;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #4F46E5;
  border-radius: 10px;
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: 500;
  color: white;
  mix-blend-mode: difference;
}

.rating {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-value {
  font-weight: 500;
  color: #1F2937;
}

.stars {
  display: flex;
  gap: 2px;
}

.icon-star {
  color: #D1D5DB;
  font-size: 12px;
}

.icon-star.filled {
  color: #FCD34D;
}

.region-analysis {
  margin-bottom: 24px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-primary {
  background: #4F46E5;
  color: white;
}

.btn-primary:hover {
  background: #4338CA;
}

.btn-outline {
  background: white;
  color: #4F46E5;
  border: 1px solid #4F46E5;
}

.btn-outline:hover {
  background: #4F46E5;
  color: white;
}

.btn-icon {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 4px;
  background: #F3F4F6;
  color: #6B7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.btn-icon:hover {
  background: #E5E7EB;
  color: #374151;
}

select {
  padding: 6px 10px;
  border: 1px solid #D1D5DB;
  border-radius: 4px;
  font-size: 14px;
  background: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .time-range-selector {
    flex-direction: column;
    align-items: stretch;
  }
  
  .range-buttons {
    flex-wrap: wrap;
  }
  
  .chart-row,
  .table-row {
    grid-template-columns: 1fr;
  }
  
  .custom-range {
    flex-wrap: wrap;
  }
}
</style>
